package com.itheima.case2.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/*
    定义所有Servlet类需要执行的相同业务逻辑
        让子类Servlet继承该类，只需要在子类中书写路径和对应方法即可
 */
//@WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求路径
        String requestURI = request.getRequestURI();// /user/selectUser   /user/updateUser
        //2.获取最后一个/的索引
        int lastIndex = requestURI.lastIndexOf("/");
        //3.截取 lastIndex + 1 的原因是lastIndex是最后/的索引，我们要/后面的字符开始一直到末尾
        //截取到的即是方法名
        String methodName = requestURI.substring(lastIndex + 1);

        try {
            //使用反射定义通用操作
            //1.获取Class类的对象  类名.class Class.forName()  对象名.getClass()
            //this表示当前类User1Servlet类的对象（即谁调用Service底层给谁创建对象）
            Class<?> clazz = this.getClass();
            //2.获取方法 selectUser
            Method m = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //3.执行方法
            m.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
